//
//  LoginViewController.m
//  MiaoTu
//
//  Created by dllo on 16/8/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "RegExp.h"
#import "MTMacro.h"
#import "ZWYNetTool.h"
#import "Login.h"
#import "Items.h"
#import "UIView+Frame.h"

@interface LoginViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIView *historyPhoneView;
@property (weak, nonatomic) IBOutlet UIButton *historyPhoneButton;

@property (nonatomic, strong) Login *loginModel;
@end

@implementation LoginViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_phoneNumberTextField endEditing:YES];
    [_passwordTextField endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpNavigationBar];
    [self setUpRoundCorner];
    [self setUpPlaceHolder];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)setUpNavigationBar {
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:0.918 green:0.416 blue:0.047 alpha:1.000];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(nothing:)];
}

- (void)backAction:(UIBarButtonItem *)barButtonItem {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)nothing:(UIBarButtonItem *)barButtonItem {
    
}

- (void)setUpPlaceHolder {
    [_phoneNumberTextField setValue:[UIColor lightTextColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTextField setValue:[UIColor lightTextColor] forKeyPath:@"_placeholderLabel.textColor"];
}

- (void)setUpRoundCorner {
    _backView.layer.cornerRadius = 4;
    _backView.layer.masksToBounds = YES;
    _backView.layer.borderWidth = 1;
    _backView.layer.borderColor = [UIColor whiteColor].CGColor;
    _phoneNumberView.layer.borderColor = [UIColor whiteColor].CGColor;
    _phoneNumberView.layer.borderWidth = 1;
    _passwordView.layer.borderColor = [UIColor whiteColor].CGColor;
    _passwordView.layer.borderWidth = 1;
    _registerButton.layer.borderWidth = 1;
    _registerButton.layer.borderColor = [UIColor whiteColor].CGColor;
    
    _historyPhoneView.layer.borderColor = [UIColor whiteColor].CGColor;
    _historyPhoneView.layer.borderWidth = 1;
    
    NSString *historyPhone = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"];
    [_historyPhoneButton setTitle:historyPhone forState:UIControlStateNormal];
    [_historyPhoneButton addTarget:self action:@selector(historyPhone:) forControlEvents:UIControlEventTouchUpInside];
}

- (IBAction)forgetPassword:(UIButton *)sender {
}

- (IBAction)registerAction:(UIButton *)sender {
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:[NSBundle mainBundle]];
    UINavigationController *registerNaVC = [[UINavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:registerNaVC animated:YES completion:^{
        
    }];
}

// 登录
- (IBAction)login:(UIButton *)sender {
    if (![self checkPhoneNumberAndPassword]) {
        [UIView animateWithDuration:2 animations:^{
            _messageLabel.alpha = 1;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:2 animations:^{
                _messageLabel.alpha = 0;
            } completion:^(BOOL finished) {
                
            }];
        }];
    } else {
        // 输入正确, 执行网络请求
        NSLog(@"输入正确");
        NSDictionary *headerDic = @{@"User-Agent":@"Dalvik/1.6.0 (Linux; U; Android 4.3; R6007 Build/JLS36C) Paros/3.2.13", @"Host":@"api.miaotu.net", @"Connection":@"Keep-Alive"};
        NSString *phoneStr = _phoneNumberTextField.text;
        NSString *passwordStr = _passwordTextField.text;
        NSString *urlStr = [NSString stringWithFormat:@"http://api.miaotu.net/v2/base/user?phone=%@&password=%@", phoneStr, passwordStr];
        
        [ZWYNetTool GET:urlStr andBody:nil andHeader:headerDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
            self.loginModel = [Login modelWithDic:result];
            
            NSString *msg = _loginModel.Msg;
            if (msg.length > 0) {
                _messageLabel.text = msg;
                [UIView animateWithDuration:2 animations:^{
                    _messageLabel.alpha = 1;
                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:2 animations:^{
                        _messageLabel.alpha = 0;
                    } completion:^(BOOL finished) {
                        
                    }];
                }];
            } else {
                // 登陆成功
                NSDictionary *loginDic = @{@"loginModel": _loginModel};
                NSNotification *loginNotification = [NSNotification notificationWithName:@"LoginNotification" object:nil userInfo:loginDic];
                [[NSNotificationCenter defaultCenter] postNotification:loginNotification];
                
                // 存到userDefaults里
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
                [[NSUserDefaults standardUserDefaults] setObject:phoneStr forKey:@"userPhone"];
                [[NSUserDefaults standardUserDefaults] setObject:passwordStr forKey:@"userPassword"];
                NSString *tocken = _loginModel.Items.Token;
                [[NSUserDefaults standardUserDefaults] setObject:tocken forKey:@"tocken"];
                [[NSUserDefaults standardUserDefaults] setObject:_loginModel.Items.HeadUrl forKey:@"headUrl"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }
        } andFailureBlock:^(NSError *error) {
            
        }];
    }
}

- (BOOL)checkPhoneNumberAndPassword {
    BOOL isMobile = [RegExp isMobile:_phoneNumberTextField.text];
    if (!isMobile) {
        _messageLabel.text = @"账号填写有误, 请检查后重新填写";
        return NO;
    } else if (_passwordTextField.text.length < 6 || _passwordTextField.text.length > 8){
        _messageLabel.text = @"密码填写有误, 请检查后重新填写";
        return NO;
    }
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    return YES;
}

- (void)textChange {
    NSString *historyPhone = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"];
    if (_phoneNumberTextField.text.length == 1 && [_phoneNumberTextField.text isEqualToString:[historyPhone substringToIndex:1]]) {
        _historyPhoneView.hidden = NO;
    } else {
        _historyPhoneView.hidden = YES;
    }
}

- (void)historyPhone:(UIButton *)btn {
    _phoneNumberTextField.text = btn.titleLabel.text;
    _historyPhoneView.hidden = YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
